import matplotlib.pyplot as plt
import numpy as np
import time

def calculate_iou(pred, target, pred_width, target_width):
    px1 = pred - pred_width
    px2 = pred + pred_width
    tx1 = target - target_width
    tx2 = target + target_width

    # 计算交集
    inter_x1 = max(px1, tx1)
    inter_x2 = min(px2, tx2)
    # if inter_x1 >= inter_x2:
    #     # inter = inter_x1 - inter_x2 + 0.5 * (pred_width + target_width)
    #     # inter = 0
    #     # iou = inter / (pred_width + target_width + inter + 1e-9)
    # else:
    inter = 0.5 * (inter_x2 - inter_x1) ** 2 / (pred_width + target_width)
    iou = inter / (pred_width + target_width - inter + 1e-9)

    return iou,inter,(pred_width + target_width - inter)

# 参数设置
width = 20
pred_width = width / 2
target_width = width / 2
target = 0  # 目标中心点位置固定为0
T1 = time.time()


# 遍历pred从-80到80
preds = np.linspace(-30, 30, 161)  # 161个点，包括-80和80
ious, inters, unions = zip(*[calculate_iou(pred, target, pred_width, target_width) for pred in preds])

# 计算1 - iou
one_minus_ious = [1 - iou for iou in ious]
T2 = time.time()
print('程序运行时间:%s毫秒' % ((T2 - T1)*1000))

# 绘图
plt.figure(figsize=(10, 6))
# plt.plot(preds, one_minus_ious, marker='o', label='1 - IoU')
plt.plot(preds, ious, marker='o', label='IoU')
# plt.plot(preds, inters, marker='x', label='Intersection')
# plt.plot(preds, unions, marker='s', label='Union')
plt.title('1 - IoU, Intersection, and Union vs Prediction Offset')
plt.xlabel('Prediction Offset')
plt.ylabel('Values')
# plt.ylim(0.2, 1.2)

plt.legend()
plt.grid(True)
plt.show()

# 打印出 preds = 20 附近的 one_minus_ious的值
print('preds = 20 附近的 one_minus_ious的值:' ,one_minus_ious[95:105])
